import {env} from "@env/environment";
import {HttpProvider} from "@providers/http";
import {App, Events, Platform} from "ionic-angular";
import {StorageProvider} from "@providers/storage";
import {DataQueryServiceProvider} from "@providers/data-query-service/data-query-service";
import {Injectable} from "@angular/core";

declare let wechat;
declare let wx;


/*
  Generated class for the WechatJsSdkProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class WechatJsSdkProvider {

  public appid;
  public jsApiList;

  constructor(public http: HttpProvider,
              private events: Events,
              private app: App,
              private storageProvider: StorageProvider,
              private platform: Platform,
              private dataQueryService: DataQueryServiceProvider,) {
  }

  initConfig() {
    if (wechat) {
      this.appid = env.wx_jssdk_config['appid'];
      this.jsApiList = env.wx_jssdk_config['webChat_jsApiList'];
      this.http.post('/trust/weixin/sign.do', {
        "url": window.location.href,
        "appid": this.appid
      }).subscribe(_data => {
        wx.config({
          debug: env.mode != 'prod', // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: this.appid,
          nonceStr: _data['data'].nonceStr,
          signature: _data['data'].signature,
          timestamp: _data['data'].timestamp,
          jsApiList: this.jsApiList // 必填，需要使用的JS接口列表
        });
      }, err => {
        console.log(err)
      });

      this.registerBackButtonAction();
    }
  }

  scanQRCode(): Promise<any> {
    return new Promise((resolve) => {
      wx.scanQRCode({
        needResult: 1,
        desc: 'scanQRCode desc',
        success: function (res) {
          res = res.resultStr;
          resolve(res);
        }
      });
    })
  }

  isWechat(): boolean {
    return wechat;
  }

  /**
   * 图片上传
   * @param {any[]} localIds
   * @returns {Promise<any>}
   */
  uploadImage(localIds: any): Promise<any> {
    let serverIdArr: any[] = [];
    let wechat_image: any[] = [];//微信图片
    let uoload_size = 0;//上传图片次数
    let fs_image: any[] = [];//文件服务器图片
    localIds.forEach(image => {
      if (typeof image != 'string' && image.origPath) {
        wechat_image.push(image);
      } else {
        fs_image.push(image);
      }
    });
    return new Promise<any>(resolve => {
      wechat_image.forEach(image => {
        wx.uploadImage({
          localId: image.origPath,
          isShowProgressTips: 0,
          success: (res) => {
            serverIdArr.push(res.serverId);
            uoload_size++;
            //上传图片次数等于微信选择图片个数
            if (uoload_size == wechat_image.length) {
              resolve({"s": serverIdArr, "f": fs_image});
            }
          }
        })
      });
    })
  }

  /**
   * 选择照片
   * @param options
   * @returns {Promise<string[]>}
   */
  chooseImage(options = {}): Promise<any> {
    let webChat_chooseImage = env.wx_jssdk_config.webChat_chooseImage || {};
    let ops = Object.assign(webChat_chooseImage, options);
    return new Promise((resolve) => {
      wx.chooseImage(Object.assign({
        success: function (res) {
          resolve(res);
        }
      }, ops));
    });
  }

  getLocalImgData(localId = {}): Promise<any> {
    return new Promise(resolve => {
      wx.getLocalImgData({
        localId: localId, // 图片的localID
        success: function (res) {
          let localData = res.localData;
          if (localData.indexOf('data:image') != 0) {
            localData = 'data:image/jpeg;base64,' +  localData;  // localData是图片的base64数据，可以用img标签显示
          }
          localData = localData.replace(/\r|\n/g, '').replace('data:image/jgp', 'data:image/jpeg');
          resolve(localData);
        }
      });
    });
  }

  /**
   * 图片预览
   * @param current
   * @param urls
   */
  previewImage(current = '', urls = []) {
    wx.previewImage({
      current: current, // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    });
  }

  //注册返回按键事件
  registerBackButtonAction() {
    //是否为返回按钮
    let isBackButtonOfIonic = undefined;
    //订阅isBackButtonOfIonic事件
    this.events.subscribe('isBackButtonOfIonic', () => {
      isBackButtonOfIonic = true;
    });
    //监听浏览器回退事件
    window.addEventListener('popstate', () => {
      //每个portal都会被初始化，在弹框被创建(create()并present()时，比较 框的类找到对应的ortal，在_views 存入框)
      //弹框，模态框、吐司框、加载框、覆盖框
      let _viewPortal = this.app._appRoot._loadingPortal.getActive()
        || this.app._appRoot._overlayPortal.getActive()
        || this.app._appRoot._modalPortal.getActive();

      //当前有弹框
      if (_viewPortal) {
        //有视图
        if (_viewPortal.instance) {
          _viewPortal.dismiss();
        }
      } else {
        //如果是返回按钮、
        if (!isBackButtonOfIonic) {
          //当前活动视图
          let activeNav = this.app.getActiveNavs();

          if (activeNav[activeNav.length - 1].canGoBack()) {
            activeNav[activeNav.length - 1].pop();
          }
        }
      }
      isBackButtonOfIonic = undefined;
    })
  }

  //保存openid
  saveOpenid() {
    //获取微信code值
    let code = this.platform.getQueryParam('code');
    let openId = this.storageProvider.read('openId');
    let userInfo = this.storageProvider.read('userInfo');
    //将openId与PARTYID进行绑定
    if (code && !openId && wechat) {
      //获取微信openId
      this.http.post('/trust/weixin/getWeChatOpenId.do', {
        json: JSON.stringify({
          "appid": this.appid,
          "code": code
        })
      }).subscribe(message => {
        //存入openId
        this.storageProvider.write('openId', message["data"]["openId"]);
        //保存openId
        this.dataQueryService.insertWXOpenId(userInfo['PARTYID'], this.storageProvider.read('openId'));
      }, error => {
      });
    } else if (code && openId && !wechat) {
      //保存openId
      this.dataQueryService.insertWXOpenId(userInfo['PARTYID'], this.storageProvider.read('openId'));
    }
  }
}
